package _17_函数式编程.Lambda._8_使用Lambda并将List类型抽象;

import _17_函数式编程.Lambda.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _8_使用Lambda并将List类型抽象 {

    public static void main(String[] args) {
        List<Apple> appleList = Arrays.asList(
                new Apple("red",150),
                new Apple("green",234),
                new Apple("green",123)
        );

        List<Apple> result;

        result = filter(appleList,
                (Apple apple) -> "green".equals(apple.getColor())
                );

        printT(result,
                (Apple apple) -> "苹果的颜色：" + apple.getColor() + "，苹果的重量：" + apple.getWeight()
                 );


        List<Integer> integerList = Arrays.asList(
                1,
                2,
                3
        );

        List<Integer> result1;
        result1 = filter(integerList,
                (Integer i) -> i >= 2
                );

        printT(result1,
                (Integer i) -> "数字：" + i
                );
    }

    /**
     * 筛选
     * @param list
     * @param tPredicate
     * @param <T>
     * @return
     */
    public static <T> List<T> filter(List<T> list, TPredicate<T> tPredicate){
        List<T> result = new ArrayList<>();
        for (T t : list){
            if (tPredicate.test(t)){
                result.add(t);
            }
        }
        return result;
    }

    /**
     * 打印信息
     * @param list
     * @param tFormatter
     * @param <T>
     */
    public static <T> void printT(List<T> list, TFormatter<T> tFormatter){
        for (T t : list){
            System.out.println(tFormatter.printT(t));
        }
    }
}
